import { UploadOutlined } from '@ant-design/icons';
import { Button, Form, message, Upload } from 'antd';
import React, { useEffect, useState } from 'react';
import { getSign } from './service'

type ImgUrl = string[];
interface ImgUploadProps {
    value?: ImgUrl;
    onChange?: (value: ImgUrl) => void;
    accessSecret?: string;
    accessId?: string;
    type?: number;
    callback?: (data: any) => any
}

const OssMultipleUpload: React.FC<ImgUploadProps> = ({ value = [], onChange, accessId, accessSecret, type, callback }) => {
    const [OSSData, setOSSData] = useState<{
        accessId: string
        callback: string
        dir: string
        expire: 1661844820
        fileName: string
        host: string
        policy: string
        signature: string
        key: string
    }>(); // Mock get OSS api

    const init = async () => {
        try {
            const response = await getSign({
                accessId: accessId,
                accessSecret: accessSecret,
                type: type || 1,
            })
            response.key = response.dir + response.fileName
            setOSSData(response);
        } catch (error) {
            message.error(error);
        }
    };

    useEffect(() => {
        init();
    }, []);

    const handleChange = ({ fileList }: any) => {
        console.log('Aliyun OSS:', fileList);
        onChange?.([...fileList]);
    };

    const onRemove = (file: any) => {
        const files = (value || []).filter((v) => v.url !== file.url);

        if (onChange) {
            onChange(files);
        }
    };

    const getExtraData = (file: any) => ({
        policy: OSSData?.policy,
        ossaccessKeyId: OSSData?.accessId,
        key: OSSData?.key + file.name.replace(/\s*/g, ''),
        dir: OSSData?.dir,
        host: OSSData?.host,

        signature: OSSData?.signature,
    });

    const beforeUpload = async (file: any) => {
        if (!OSSData) return false;
        const expire = Number(OSSData.expire) * 1000;

        if (expire < Date.now()) {
            await init();
        }

        file.url = OSSData.host + "/" + OSSData.key + file.name.replace(/\s*/g, '');
        return file;
    };

    const uploadProps = {
        name: 'file',
        fileList: value,
        action: OSSData?.host,
        onChange: handleChange,
        onRemove,
        maxCount: 6,
        data: getExtraData,
        beforeUpload,
        previewFile: (file: File) => {
            return file?.url || file?.thumbUrl
        }
    };
    return (
        <Upload {...uploadProps}>
            <Button icon={<UploadOutlined />}>上传(最多6张)</Button>
        </Upload>
    );
};


export default OssMultipleUpload;